import requests
import time
import os
import sys

# 获取当前脚本的目录
current_dir = os.path.dirname(os.path.abspath(__file__))

# 将 python-periphery-master 添加到 Python 搜索路径
sys.path.append(os.path.join(current_dir, "python-periphery-master"))

from periphery import GPIO

# 定义 GPIO 和 API 配置
ERROR_GPIO_PIN = 500  # GPIO 引脚编号
API_URL = "http://172.21.22.50:5000/api/error"

# 初始化 GPIO
Error_GPIO = GPIO(ERROR_GPIO_PIN, "out")

def fetch_api_data():
    #print("正在调用 API...")
    try:
        response = requests.get(API_URL, timeout=5)
        if response.status_code == 200:
            data = response.json()
            #print("成功获取数据：", data)
            return data
        else:
            print("请求失败，状态码：", response.status_code)
            return None
    except requests.ConnectionError:
        print("无法连接到 API 服务器，请检查网络或服务器地址。")
    except requests.Timeout:
        print("请求超时，请检查服务器是否正常运行。")
    except Exception as e:
        print(f"发生错误：{e}")
    return None

if __name__ == "__main__":
    try:
        while True:
            # 获取数据
            data = fetch_api_data()
            if data:
                # 检查 Warning 状态
                if data.get("SystemStatus") == "1":
                    print("系统状态不正常，设置 GPIO 为高电平")
                    Error_GPIO.write(True)
                else:
                    # print("系统状态正常，设置 GPIO 为低电平")
                    Error_GPIO.write(False)

            # 每 1 秒检查一次
            time.sleep(1)

    except KeyboardInterrupt:
        print("检测到退出请求 (Ctrl+C)，程序终止。")
    finally:
        # 确保释放 GPIO
        Error_GPIO.close()
        print("GPIO 已关闭，程序结束。")
